// 阻止不登录进入管理页面
const nickname = sessionStorage.getItem('nickname');
if (nickname !== "Admin") {
    alert("权限不足，请登录管理员账号");
    setTimeout(() => {
        window.location.href = "login.html";
    }, 100);
}

////////////////////主页面///////////////////////

// 自动更新时间
function updateTime() {
    const now = new Date();
    document.getElementById('time').textContent = now.toLocaleTimeString();
}
setInterval(updateTime, 1000);

// 根据选择的菜单栏显示不同页面以及运行不同函数
document.querySelectorAll('.sidebar a').forEach(link => {
    link.addEventListener('click', function(event) {
        event.preventDefault();
        const targetId = this.getAttribute('data-target');
        document.querySelectorAll('.content').forEach(div => {
            div.classList.remove('active');
        });
        const targetDiv = document.getElementById(targetId);
        targetDiv.classList.add('active');
        switch(targetId){
            case "1":
                getUsers();
                break;
            case "2":
                getProducts();
                break;
            case "3":
                getSecKillActivities();
                break
            case "4" :
                getAllOrders();
                break;
            case "5":
                getMessage();
                setInterval(getMessage,5000);
                break;
        }
    });
});

///////////////////用户管理/////////////////////

// 获取用户数据
function getUsers(){
    $.ajax({
        url:"/UserForAdmin",
        method:"GET",
        data:{type:"get"},
        dataType:"json",
        success:function(dataString) {
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const usersTableBody = document.getElementById('usersTableBody');
            usersTableBody.innerHTML = '';

            // 展示用户信息
            data.forEach(user => {
                let status;
                if (user.state === 1){
                    status = "正常";
                } else if (user.state === 0){
                    status = "禁用";
                }
                const row = document.createElement('tr');
                row.innerHTML = `
                    <tr>
                        <td>${user.id}</td>
                        <td><img alt="头像" data-id="${user.id}" src=${user.avatar} class="avatar"></td>
                        <td class="editable" data-id="${user.id}" data-key="account">${user.account}</td>
                        <td class="editable" data-id="${user.id}" data-key="password">${user.password}</td>
                        <td class="editable" data-id="${user.id}" data-key="name">${user.name}</td>
                        <td class="editable" data-id="${user.id}" data-key="balance">${user.balance}</td>
                        <td class="editable" data-id="${user.id}" data-key="orders">${user.orders}</td>
                        <td>${user.createTime}</td>
                        <td>${user.updateTime}</td>
                        <td>${status}</td>
                        <td>
                            <label class="capsule-switch">
                                <input type="checkbox" data-id="${user.id}" ${user.state === 1 ? 'checked' : ''} >
                                <span class="slider"></span>
                            </label>
                        </td>
                        <td>
                            <button data-id="${user.id}" class="user-delete-btn" >删除</button>
                        </td>
                    </tr>
                `;
                usersTableBody.appendChild(row);
            });

            // 添加启用按钮的点击事件
            document.querySelectorAll('.capsule-switch input').forEach(switchElement => {
                switchElement.addEventListener('change', function() {
                    const userId = this.getAttribute('data-id');
                    const newState = this.checked ? 1 : 0;
                    updateUser(userId,"state",newState);
                });
            });

            // 添加可编辑单元格的点击事件
            document.addEventListener('click', function(event) {
                // 查找最近的带有 'editable' 类的元素
                const cell = event.target.closest('.editable');
                // 如果点击的不是可编辑单元格，退出
                if (!cell) return;
                // 防止重复创建输入框
                if (cell.querySelector('input')) return;
                // 获取单元格的键和当前值
                const key = cell.getAttribute('data-key');
                const currentValue = cell.textContent;
                const userId = cell.getAttribute('data-id');
                // 创建输入框并设置其初始值
                const input = document.createElement('input');
                input.type = 'text';
                input.value = currentValue;
                // 清空单元格内容
                cell.innerHTML = '';
                // 将输入框添加到单元格中
                cell.appendChild(input);
                // 使输入框获得焦点
                input.focus();
                // 输入框失去焦点时的处理逻辑
                input.addEventListener('blur', () => {
                    // 去除首尾空格
                    const newValue = input.value.trim();
                    // 转义HTML并更新单元格内容
                    cell.innerHTML = escapeHtml(newValue);
                    updateUser(userId,key,newValue);
                });
            });

            // 转义HTML函数，防止XSS攻击
            function escapeHtml(str) {
                return str.replace(/[&<>"']/g, function(match) {
                    const escape = {
                        '&': '&amp;',
                        '<': '&lt;',
                        '>': '&gt;',
                        '"': '&quot;',
                        "'": '&#39;'
                    };
                    return escape[match];
                });
            }

            // 添加头像点击事件
            document.querySelectorAll('.avatar').forEach(img => {
                img.addEventListener('click', function() {
                    const modal = document.getElementById('avatarModal');
                    const userId = this.getAttribute('data-id');
                    modal.style.display = "block";
                    const selectedAvatar = this;
                    document.querySelectorAll('.avatar-option').forEach(option => {
                        option.addEventListener('click', function() {
                            selectedAvatar.src = this.src;
                            modal.style.display = "none";
                            let relativePath = this.src.replace("http://127.0.0.1:10086", ".");
                            updateUser(userId,"avatar",relativePath);
                        });
                    });
                });
            });

            // 关闭头像选择弹窗
            document.querySelector('.close').addEventListener('click', function() {
                document.getElementById('avatarModal').style.display = "none";
            });

            // 添加删除按钮的点击事件
            document.querySelectorAll('.user-delete-btn').forEach(button => {
                button.addEventListener('click', function() {
                    const userId = this.getAttribute('data-id');
                    deleteUser(userId);
                });
            });
        }
    })
}

// 点击空白区域关闭选择头像弹窗
window.onclick = function(event) {
    const modal = document.getElementById('avatarModal');
    if (event.target === modal) {
        modal.style.display = "none";
    }
}

// 点击添加用户按钮显示添加弹窗
document.getElementById('addUserBtn').addEventListener('click', function() {
    document.getElementById('addUserModal').style.display = 'block';
});

// 点击关闭按钮关闭添加弹窗
document.querySelectorAll('.close').forEach(span => {
    span.addEventListener('click', function() {
        this.parentElement.parentElement.style.display = 'none';
    });
});

// 点击空白区域关闭添加弹窗
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
};

// 点击选择头像按钮显示选择头像弹窗
document.getElementById('selectAvatarBtn').addEventListener('click', function() {
    document.getElementById('avatarModal').style.display = 'block';
});

// 点击头像选项选择头像
document.querySelectorAll('.avatar-option').forEach(img => {
    img.addEventListener('click', function() {
        document.getElementById('selectedAvatar').src = this.src;
        document.getElementById('avatarModal').style.display = 'none';
    });
});

// 点击添加用户按钮提交表单
document.getElementById('addUserForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);
    const user = {};
    formData.forEach((value, key) => {
        user[key] = value;
    });
    user.avatar = document.getElementById('selectedAvatar').src;
    // 图片裁剪路径，传给后端请使用相对路径
    let relativePath = user.avatar.replace("http://127.0.0.1:10086", ".");
    addUser(relativePath,user.account,user.password,user.name);
    document.getElementById('addUserModal').style.display = 'none';
});

// 添加搜索按钮的点击事件（纯前端实现）
document.querySelectorAll('.searchBtn').forEach(button => {
    button.addEventListener('click', function() {
        // 获取对应的搜索框
        const searchInput = this.previousElementSibling;
        const searchValue = searchInput.value.toLowerCase();
        const rows = document.querySelectorAll('#usersTableBody tr');
        rows.forEach(row => {
            const account = row.querySelector('td[data-key="account"]').textContent.toLowerCase();
            const name = row.querySelector('td[data-key="name"]').textContent.toLowerCase();
            if (account.includes(searchValue) || name.includes(searchValue)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
});

// 更新用户
function updateUser(userId,key,value) {
    $.ajax({
        url: "/UserForAdmin",
        type: "get",
        data: {
            "type": "update",
            "userId": userId,
            "key": key,
            "value": value
        },
        success: function (data) {
            if (data === "success") {
                showInfo(`更新成功！`);
                getUsers();
            }
        }
    })
}

// 删除用户
function deleteUser(userId) {
    $.ajax({
        url: "/UserForAdmin",
        type: "get",
        data: {
            "type": "delete",
            "userId": userId
        },
        success: function (data) {
            if (data === "success") {
                showInfo(`删除成功！`);
                getUsers();
            }
        }
    })
}

// 添加用户
function addUser(avatar,account,password,name){
    $.ajax({
        url: "/UserForAdmin",
        type: "get",
        data: {
            "type": "add",
            "avatar": avatar,
            "account": account,
            "password": password,
            "nickName": name
        },
        success: function (data) {
            if (data === "success") {
                showInfo(`添加成功！`);
                getUsers();
            }
        }
    })
}

//////////////////商品管理//////////////////////

// 获取商品
function getProducts() {
    let keyword = $("#searchGoodsInput").val();
    if (keyword === '' || keyword === null) {
        keyword = '%';
    }
    $.ajax({
        url: "/goods",
        type: "get",
        data: {num:8,keyword:keyword},
        dataType: "json",
        success: function (dataString) {
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const goodsTableBody = document.getElementById('goodsTableBody');
            goodsTableBody.innerHTML = '';
            // 每页显示的行数
            const rowsPerPage = 5;
            // 获取总页数（数组长度除以每页行数）
            const totalPages = Math.ceil(data.length / rowsPerPage);
            // 初始页数
            let currentPage = 1;

            // 展示商品信息
            function displayPage(page) {
                goodsTableBody.innerHTML = '';
                const start = (page - 1) * rowsPerPage;
                const end = start + rowsPerPage;
                const pageData = data.slice(start, end);
                pageData.forEach(function (item) {
                    let classify;
                    if (item.classify === 1){
                        classify = "家电";
                    } else if (item.classify === 2) {
                        classify = "数码";
                    } else if (item.classify === 3) {
                        classify = "文具";
                    } else if (item.classify === 4) {
                        classify = "箱包";
                    } else if (item.classify === 5) {
                        classify = "服饰";
                    } else if (item.classify === 6) {
                        classify = "运动";
                    }
                    let type;
                    if (item.state === 0) {
                        type = "上架";
                    } else if (item.state === 1) {
                        type = "下架";
                    }
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${item.id}</td>
                        <td><img alt="图片" src=${item.image} class="image"></td>
                        <td class="editable" data-id="${item.id}" data-key="name" style="width:700px">${item.name}</td>
                        <td class="editable" data-id="${item.id}" data-key="price">${item.price}</td>
                        <td class="editable" data-id="${item.id}" data-key="inventory">${item.inventory}</td>
                        <td class="category-cell" data-id="${item.id}" data-classify="${item.classify}">${classify}</td>
                        <td>${type}</td> 
                        <td>
                            <label class="capsule-switch">
                                <input type="checkbox" data-id="${item.id}" ${item.state === 0 ? 'checked' : ''} >
                                <span class="slider"></span>
                            </label>
                        </td>
                        <td>
                            <button data-id="${item.id}" class="goods-delete-btn" >删除</button>
                        </td>
                    `;
                    goodsTableBody.appendChild(row);
                });

                // 添加删除商品的点击事件
                document.querySelectorAll('.goods-delete-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        const goodsId = this.getAttribute('data-id');
                        deleteProduct(goodsId);
                    });
                });

                // 添加启用按钮的点击事件
                document.querySelectorAll('.capsule-switch input').forEach(switchElement => {
                    switchElement.addEventListener('change', function() {
                        const goodsId = this.getAttribute('data-id');
                        const newState = this.checked ? 0 : 1;
                        updateProduct(goodsId, "state", newState);
                    });
                });

                // 添加可编辑单元格的点击事件
                document.querySelectorAll('.editable').forEach(cell => {
                    cell.addEventListener('click', function () {
                        // 防止重复创建输入框
                        if (cell.querySelector('input')) return;
                        const key = cell.getAttribute('data-key');
                        const currentValue = cell.textContent;
                        const itemId = cell.getAttribute('data-id');
                        const input = document.createElement('input');
                        input.type = 'text';
                        input.value = currentValue;
                        // 清空单元格内容
                        cell.innerHTML = '';
                        // 将输入框添加到单元格中
                        cell.appendChild(input);
                        // 使输入框获得焦点
                        input.focus();
                        // 输入框失去焦点时的处理逻辑
                        input.addEventListener('blur', () => {
                            // 去除首尾空格
                            const newValue = input.value.trim();
                            // 转义HTML并更新单元格内容
                            cell.innerHTML = escapeHtml(newValue);
                            updateProduct(itemId, key, newValue);
                        });
                    });
                });

                // 添加分类单元格点击事件
                document.querySelectorAll('.category-cell').forEach(cell => {
                    cell.addEventListener('click', function () {
                        const categorySelectTemplate = document.getElementById('categorySelectTemplate');
                        const categorySelect = categorySelectTemplate.cloneNode(true);
                        categorySelect.id = '';
                        categorySelect.classList.add('category-select');
                        categorySelect.style.display = 'block';
                        categorySelect.setAttribute('data-id', this.getAttribute('data-id'));
                        // 设置初始值
                        categorySelect.value = this.getAttribute('data-classify');
                        // 清空单元格内容
                        this.innerHTML = ""
                        this.appendChild(categorySelect);
                        // 聚焦下拉框
                        categorySelect.focus();
                        // 监听下拉框变化事件
                        categorySelect.addEventListener('change', function (event) {
                            const categoryId = event.target.value;
                            const categoryName = event.target.options[event.target.selectedIndex].text;
                            const productId = event.target.getAttribute('data-id');
                            updateProduct(productId, "classify", categoryId);
                            // 隐藏下拉框并恢复单元格内容
                            event.target.style.display = 'none';
                            const cell = event.target.parentElement;
                            setTimeout(() => {
                                // 确保节点仍然存在
                                if (cell) {
                                    cell.innerHTML = categoryName;
                                }
                            }, 50);
                        });
                        // 监听下拉框失焦事件
                        // 有bug，在点击下拉框松开后会立即判定为失焦，导致下拉框在鼠标松开后就消失，需要长按并滑动到下拉框
                        // 此问题暂不解决，需要重写这块鼠标点击事件逻辑
                        categorySelect.addEventListener('blur', function (event) {
                            const cell = event.target.parentElement;
                            cell.innerHTML = event.target.options[event.target.selectedIndex].text;
                        });
                    });
                });
            }

            // 纯前端的分页显示（无需前后端交互，可实时更新页数）
            // 生成分页信息
            function createPagination() {
                // 生成上一页按钮
                const pagination = document.getElementById('pagination');
                pagination.innerHTML = '';
                const prevButton = document.createElement('button');
                prevButton.innerText = '上一页';
                prevButton.disabled = currentPage === 1;
                prevButton.addEventListener('click', function () {
                    if (currentPage > 1) {
                        currentPage--;
                        displayPage(currentPage);
                        updatePagination();
                    }
                });
                pagination.appendChild(prevButton);

                // 生成页码按钮
                for (let i = 1; i <= totalPages; i++) {
                    const pageButton = document.createElement('button');
                    pageButton.innerText = i;
                    pageButton.disabled = i === currentPage;
                    pageButton.addEventListener('click', function () {
                        currentPage = i;
                        displayPage(currentPage);
                        updatePagination();
                    });
                    pagination.appendChild(pageButton);
                }

                // 生成下一页按钮
                const nextButton = document.createElement('button');
                nextButton.innerText = '下一页';
                nextButton.disabled = currentPage === totalPages;
                nextButton.addEventListener('click', function () {
                    if (currentPage < totalPages) {
                        currentPage++;
                        displayPage(currentPage);
                        updatePagination();
                    }
                });
                pagination.appendChild(nextButton);
            }

            // 更新分页信息
            function updatePagination() {
                const buttons = document.querySelectorAll('#pagination button');
                buttons.forEach((button, index) => {
                    if (index === 0) {
                        button.disabled = currentPage === 1;
                    } else if (index === buttons.length - 1) {
                        button.disabled = currentPage === totalPages;
                    } else {
                        button.disabled = parseInt(button.innerText) === currentPage;
                    }
                });
            }
            // 运行生成分页
            createPagination();
            // 默认显示第一页
            displayPage(1);
        }
    });
}

// 转义HTML函数，防止XSS攻击
function escapeHtml(str) {
    return str.replace(/[&<>"']/g, function (match) {
        const escape = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '\"': '&quot;',
            "'": '&#39;'
        };
        return escape[match];
    });
}

// 获取弹窗元素
const modal = document.getElementById("myModal");
const btn = document.getElementById("addGoodsBtn");
const span = document.getElementsByClassName("close")[0];
// 如果用户按下按钮，则打开弹窗
btn.onclick = function() {
    modal.style.display = "block";
}
// 如果用户按下 <span> 标签 (x), 关闭弹窗
span.onclick = function() {
    modal.style.display = "none";
}
// 如果用户点击弹窗以外区域，关闭弹窗
window.onclick = function(event) {
    if (event.target === modal) {
        modal.style.display = "none";
    }
}

// 简易上传图片
document.getElementById('uploadBtn').addEventListener('click', function(event) {
    event.preventDefault();
    const input = $('#uploadImage')[0];
    if (input.files.length === 0) {
        showInfo('请选择图片');
        return;
    }
    if (input.files[0].size > 1000000) {
        showInfo('不支持上传大于1MB的图片文件');
        return;
    }
    const file = input.files[0];
    const reader = new FileReader();
    reader.onload = function(e) {
        const base64String = e.target.result;
        uploadToServer(base64String);
    };
    reader.readAsDataURL(file);
});

let imagePath;
// 发送 base64String 到服务器
function uploadToServer(base64String) {
    $.ajax({
        url: '/upData',
        type: 'get',
        data: {
            'base64': base64String
        },
        success: function(response) {
            showInfo('图片上传成功');
            // 裁剪图片路径用于界面展示上传图
            imagePath = response.replace("html/", "./").replace("\\", "");
            const uploadImage = document.getElementById("image");
            uploadImage.src = imagePath;
        },
        error: function() {
            showInfo('上传失败，请重试');
        }
    });
}

// 更新商品信息的函数
function updateProduct(itemId, key, value) {
    $.ajax({
        url:"/goodsForAdmin",
        type:"get",
        data:{
            type:"update",
            name:"goods",
            id:itemId,
            key:key,
            value:value
        },
        success:function (data) {
            if (data >= 1) {
                showInfo('更新成功');
                getProducts();
            } else {
                showInfo('更新失败');
            }
        }
    })
}

// 删除商品信息的函数
function deleteProduct(id) {
    $.ajax({
        url:"/goodsForAdmin",
        type:"get",
        data:{
            type:"delete",
            name:"goods",
            id:id
        },
        success:function (data) {
            if (data >= 1) {
                showInfo('删除成功');
                getProducts();
            } else {
                showInfo('删除失败');
            }
        }
    })
}

// 插入商品信息函数
document.getElementById('productForm').addEventListener('submit', function(event) {
    // 阻止表单提交
    event.preventDefault();
    // 获取表单元素
    const form = event.target;
    const formData = new FormData(form);
    // 获取图片路径
    const image = imagePath;
    // 获取下拉框选项对应的数字
    const categoryMapping = {
        '家电': 1,
        '数码': 2,
        '文具': 3,
        '箱包': 4,
        '服饰': 5,
        '运动': 6
    };
    // 创建对象存储所有值
    const data = {
        image: image,
        name: formData.get('name'),
        price: formData.get('price'),
        inventory: formData.get('stock'),
        classify: categoryMapping[formData.get('category')]
    };
    $.ajax({
        url:"/goodsForAdmin",
        type:"get",
        data: {
            type:"addGoods",
            image:data.image,
            name:data.name,
            price:data.price,
            inventory:data.inventory,
            classify:data.classify
        },
        success:function (data) {
            if (data >= 1) {
                showInfo('添加成功');
                getProducts();
            } else {
                showInfo('添加失败');
            }
        }
    })
});

/////////////////秒杀活动管理////////////////////

// 获取商品名称
function getName(id) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: "/goods",
            type: "get",
            data: {num: 10,id: id},
            dataType: "json",
            success: function(dataString) {
                const jsonStringArray = JSON.parse(dataString);
                const data = jsonStringArray[id];
                resolve(data);
            },
            error: function(error) {
                reject(error);
            }
        });
    });
}

// 获取秒杀信息
function getSecKillActivities() {
    $.ajax({
        url: "/goods",
        type: "get",
        data: {num: 9},
        dataType: "json",
        success: function(dataString) {
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const secKillTableBody = document.getElementById('secKillTableBody');
            secKillTableBody.innerHTML = '';
            data.forEach(item => {
                const row = document.createElement(`tr`);
                row.dataset.id = item.id;
                row.innerHTML = `
                    <td>${item.id}</td>
                    <td class="tooltip">${item.goodsId}
                        <span class="tooltiptext"></span>
                    </td>
                    <td>${item.startTime}</td>
                    <td>${item.endTime}</td>
                    <td>${item.price}</td>
                    <td>${item.stock}</td>
                    <td>${item.number}</td>
                    <td>
                        <button data-id="${item.id}" class="secKill-delete-btn">删除</button>
                    </td>
                `;
                secKillTableBody.appendChild(row);

                // 添加鼠标悬浮事件监听器显示商品名称，使用闭包确保 item.goodsId 正确传递
                (function(goodsId) {
                    const tooltip = row.querySelector('.tooltip');
                    tooltip.addEventListener('mouseenter', function() {
                        const tooltipText = tooltip.querySelector('.tooltiptext');
                        getName(goodsId).then(name => {
                            tooltipText.textContent = name;
                        }).catch(error => {
                            console.error(error);
                        });
                    });
                })(item.goodsId);
            });
        }
    });
}

// 全新研究的写法，在界面加载完毕时，通过给表格添加监听，根据表格列数索引对单元格进行不同操作
// 怎么没早点研究呢，害得前面两个要写一堆
document.addEventListener('DOMContentLoaded', function() {
    const secKillTableBody = document.getElementById('secKillTableBody');

    // 给表格添加事件监听
    secKillTableBody.addEventListener('click', function(event) {
        const target = event.target;
        // startTime, endTime, price, stock, number 列的索引
        const editableColumns = [2, 3, 4, 5, 6];
        if (target.tagName === 'TD' && editableColumns.includes(target.cellIndex)) {
            const currentValue = target.textContent;
            const input = document.createElement('input');
            // 根据列索引设置输入框类型
            input.type = target.cellIndex < 4 ? 'time' : 'text';
            input.value = currentValue;
            // 设置不同大小
            if (input.type === 'time') {
                input.style.width = '85px';
                input.style.height = '25px';
            } else {
                input.style.width = '55px';
                input.style.height = '25px';
            }
            target.textContent = '';
            target.appendChild(input);
            input.focus();
            input.addEventListener('blur', function () {
                const newValue = input.value;
                // 使用 dataset 获取 id
                const id = target.parentElement.dataset.id;
                let key;
                // 根据列索引设置 key
                switch (target.cellIndex) {
                    case 2:
                        key = 'start_time';
                        break;
                    case 3:
                        key = 'end_time';
                        break;
                    case 4:
                        key = 'price';
                        break;
                    case 5:
                        key = 'limit';
                        break;
                    case 6:
                        key = 'number';
                        break;
                }
                target.textContent = newValue;
                // 处理修改后的字段、值和ID
                UpdateSecKill(id, key, newValue);
            });
        }
    });

    // 添加删除按钮的点击事件监听器
    secKillTableBody.addEventListener('click', function(event) {
        const target = event.target;
        if (target.classList.contains('secKill-delete-btn')) {
            const row = target.closest('tr');
            const id = row.dataset.id;
            // 处理删除操作
            DeleteSecKill(id);
        }
    });
});

// 修改秒杀活动
function UpdateSecKill(id, key, value) {
    $.ajax({
        url: "/goodsForAdmin",
        type: "get",
        data: {
            type: "update",
            name: "activitys",
            id: id,
            key: key,
            value: value
        },
        success: function (data) {
            if (data >= 1) {
                showInfo('修改成功');
                getSecKillActivities();
            } else {
                showInfo('修改失败');
            }
        }
    });
}

// 删除秒杀活动
function DeleteSecKill(id) {
    $.ajax({
        url: "/goodsForAdmin",
        type: "get",
        data: {
            type: "delete",
            name: "activitys",
            id: id,
        },
        success: function (data) {
            if (data >= 1) {
                showInfo('删除成功');
                getSecKillActivities();
            } else {
                showInfo('删除失败');
            }
        }
    });
}

// 获取弹窗元素
let AcModal = document.getElementById("addActivityModal");
let AcBtn = document.getElementById("addActivityBtn");
let AcSpan = document.getElementsByClassName("close")[0];
// 点击按钮打开弹窗
AcBtn.onclick = function() {
    AcModal.style.display = "block";
    getClickProduct(1);
}
// 点击 <span> (x) 关闭弹窗
AcSpan.onclick = function() {
    AcModal.style.display = "none";
}
// 在用户点击弹窗外部时关闭弹窗
window.onclick = function(event) {
    if (event.target === AcModal) {
        AcModal.style.display = "none";
    }
}

// 获取所有商品名字
getGoodsName();
function getGoodsName() {
    $.ajax({
        url: "/goods",
        type: "get",
        data: {num: 10},
        dataType: "json",
        success: function (dataString) {
            const products = JSON.parse(dataString);
            populateProductSelect(products);
        }
    });
}

// 动态生成商品名选项
function populateProductSelect(products) {
    const productSelect = document.getElementById('productId');
    productSelect.innerHTML = ''; // 清空之前的选项
    productSelect.style.height = "33px";
    productSelect.style.border = "1px solid #ccc";
    for (const id in products) {
        if (products.hasOwnProperty(id)) {
            const option = document.createElement('option');
            option.value = id;
            // 限制文本长度
            option.textContent = truncateText(products[id], 28);
            productSelect.appendChild(option);
        }
    }
}

// 限制长度
function truncateText(text, maxLength) {
    if (text.length > maxLength) {
        return text.substring(0, maxLength) + '...';
    }
    return text;
}

// 点击商品时获取商品详细信息
document.getElementById("productId").addEventListener("change",function (){
    const id = document.getElementById("productId").value;
    getClickProduct(id);
})

let productData;
// 获取所点击的商品所有信息
function getClickProduct(id){
    $.ajax({
        url:"/goods",
        type:"GET",
        data:{
            num:"2",
            id:id
        },
        dataType:"json",
        success:function(dataString){
            const jsonStringArray = JSON.parse(dataString);
            productData = jsonStringArray.map(item => JSON.parse(item));
        }
    })
}

// 活动结束时间不能早于开始时间
document.getElementById("endTime").addEventListener('change', function () {
    const startTime = document.getElementById("startTime").value;
    const endTime = document.getElementById("endTime").value;
    if (endTime < startTime) {
        showInfo("活动结束时间不能早于开始时间");
        document.getElementById("endTime").value = "";
    }
});

// 活动价格不得高于原商品价格
document.getElementById("ACPrice").addEventListener('change', function () {
    const ACPrice = document.getElementById("ACPrice").value;
    const price = productData[0].price;
    if (ACPrice > price) {
        showInfo("活动价格不能高于原商品价格");
        document.getElementById("ACPrice").value = "";
    }
});

// 活动库存数量不得高于原商品库存
document.getElementById("ACStock").addEventListener('change', function () {
    const ACStock = document.getElementById("ACStock").value;
    const stock = productData[0].inventory;
    if (ACStock > stock) {
        showInfo("活动库存数量不能高于原商品库存");
        document.getElementById("ACStock").value = "";
    }
});

// 活动限购购买数量不得高于活动库存
document.getElementById("limit").addEventListener('change', function () {
    const limit = document.getElementById("limit").value;
    const ACStock = document.getElementById("ACStock").value;
    if (limit > ACStock) {
        showInfo("活动限购购买数量不得高于活动库存");
        document.getElementById("limit").value = "";
    }
});

// 提交按钮点击事件
document.getElementById("submitBtn").onclick = function() {
    const productId = document.getElementById("productId").value;
    const startTime = document.getElementById("startTime").value;
    const endTime = document.getElementById("endTime").value;
    const price = document.getElementById("ACPrice").value;
    const limit = document.getElementById("limit").value;
    const stock = document.getElementById("ACStock").value;
    addSecKill(productId, startTime, endTime, price, limit, stock);
}

// 添加秒杀活动
function addSecKill(productId, startTime, endTime, price, limit, stock) {
    $.ajax({
        url: "/goodsForAdmin",
        type: "get",
        data: {
            type: "addSecKillGoods",
            productId: productId,
            startTime: startTime,
            endTime: endTime,
            price: price,
            limit: limit,
            stock: stock
        },
        success: function (data) {
            if (data >= 1) {
                showInfo('添加成功');
                getSecKillActivities();
            } else {
                showInfo('添加失败');
            }
        }
    });
}

///////////////////订单管理/////////////////////

// 获取所有订单
function getAllOrders() {
    let value = document.getElementById('searchOrdersInput').value;
    if (value == null || value === '') {
        value = "%";
    }
    $.ajax({
        url:"/orders",
        type:"GET",
        data: {
            value:value,
            type:"get",
            userId:"0"
        },
        dataType:"json",
        success: function (dataString) {
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const ordersTableBody = document.getElementById('ordersTableBody');
            ordersTableBody.innerHTML = '';
            data.forEach(item => {
                let status;
                if (item.state === "1") {
                    status = "已支付";
                } else if (item.state === "2") {
                    status = "未支付";
                } else if (item.state === "3") {
                    status = "退款中";
                } else if (item.state === "4") {
                    status = "已退款";
                } else if (item.state === "5") {
                    status = "已取消";
                }
                const row = document.createElement(`tr`);
                row.innerHTML = `
                    <td>${item.id}</td>
                    <td>${item.userId}</td>
                    <td><img alt="图片" src=${item.image} class="image"></td>
                    <td width="600px">${item.name}</td>
                    <td>${item.number}</td>
                    <td>${item.price}</td>
                    <td>${status}</td>
                    <td>${item.time}</td>
                `;
                ordersTableBody.appendChild(row);
            })
        }
    })
}

///////////////////客服聊天/////////////////////

// 发送消息
function sendMessage() {
    const messageInput = document.getElementById('adminMessage');
    const messageText = messageInput.value;
    if (messageText.trim() === '') return
    $.ajax({
        url: "/support",
        type: "get",
        data: { type: "insert", user: "admin", text: messageText },
        success: function () {
            // 清空输入框
            messageInput.value = '';
            // 发送消息后刷新消息列表
            getMessage();
        }
    });
}

// 获取聊天信息
function getMessage() {
    $.ajax({
        url: "/support",
        type: "get",
        data: { type: "get" },
        dataType: "json",
        success: function (dataString) {
            const data = JSON.parse(dataString);
            // 加载消息列表
            loadChatMessages(data);
        }
    });
}

// 加载聊天记录
function loadChatMessages(data) {
    const chatBody = document.querySelector('.chat-body');
    chatBody.innerHTML = "";
    // 根据数据生成消息列表
    data.forEach(entry => {
        const newMessage = document.createElement('div');
        // 设置不同样式
        if (entry.role === 'admin') {
            newMessage.classList.add('chat-message', 'admin');
        } else if (entry.role === 'user') {
            newMessage.classList.add('chat-message', 'user');
        }
        const avatar = document.createElement('img');
        avatar.src = 'https://via.placeholder.com/40';
        avatar.classList.add('avatar');
        const messageContent = document.createElement('div');
        messageContent.classList.add('message-content');
        messageContent.textContent = entry.message;
        // 设置不同样式
        if (entry.role === 'admin') {
            newMessage.appendChild(messageContent);
            newMessage.appendChild(avatar);
        } else if (entry.role === 'user') {
            newMessage.appendChild(avatar);
            newMessage.appendChild(messageContent);
        }
        chatBody.appendChild(newMessage);
    });
    chatBody.scrollTop = chatBody.scrollHeight;
}